#!/bin/bash
###########################User Changeable Data############################
mysql_username="CHANGEME"
mysql_password="CHANGEME"
DIR=/mnt/tv
#use the ids its probably better
imgurapi=CHANGEME
hdhomerun_ip1=13127056
hdhomerun_ip2=13202689 
comskip_dir=/root/comskip81_036_donators
projectx_dir=/root/projectx/Project-X_0.91.0
mangler=/root/newsmangler/mangler.py
mangler_config=/root/newsmangler/docs/sample.conf
rar=/opt/bin/rar
fixgop=/root/hdhomerun-tv-recoder/scripts/fixgop.sh
SCPHOST=CHANGEME
SCPBASE=CHANGEME #You have to escape the spaces yourself
SCPUSERNAME=CHANGEME

FTPUSERNAME=CHANGEME
FTPPASSWORD=CHANGEME
FTPHOST=CHANGEME
FTPDIR=CHANGEME
#NZBDIR is probably the home directory of the user running this cronjob my case /root
NZBDIR=/root
##########################Finished with User Changeable Data################

trap ctrl_c INT

#Some Files we need
ffmpeg=`which ffmpeg`
hdhomerun_config=`which hdhomerun_config`
wine=`which wine`
java=`which java`
mysql=`which mysql`
ssh=`which ssh`
scp=`which scp`
par=`which par2create`
xml=`which xml`
mediainfo=`which mediainfo`
mkvmerge=`which mkvmerge`
scp=`which scp`
ncftpput=`which ncftpput`
curl=`which curl`

function help {
	echo "Record Script By John Hass for use with the hdhomerun and hdhomerun_config BSD License"
	echo
	echo "Usage: $0 -channel [channel_number] -length [minutes_to_record] -tuner [tuner_number_to_use] -filename [filename.to.make] -id [The mysql id]"
	echo "EX: $0 -channel 261 -length 60 -tuner 2 -filename The.Real.Housewives.of.Orange.County.S07E10.Cabin.Fever" -id 1
	echo
	echo
	echo " -channel...............The channel to tune to"
	echo " -length................The length in minutes to record for"
	echo " -tuner.................The tuner to use (small hdhomerun is 0-2,0-5 for the big hdhome run or more then one little one see variable hdhomerun_ip{1-2})"
	echo " -filename..............The filename (and Directory) to save in $DIR"
	echo " -id....................The Mysql ID to update when we are done (Optional)"
	echo " -wbs...................Amount of seconds to wait before starting the recording"
	echo " -usenet................Post the finished .mkv (rar) to usenet (Optional)"
	echo " -nzbmatrix.............Post the finished .nzb to nzbmatrix (Optional) Also see the nzbmatrix readme on how to login"
	echo " -scp...................scp the final mkv file... you need to keyshare!!!"
	echo " -ftp...................ftp the final mkv file"

	exit 1
}



if [ $# -lt 3 ] ; then
	help
fi

WBS=0
while [ $# -gt 0 ] ; do
	case $1 in
		-channel) CHANNEL=$2 ; shift 2 ;;
		-length) LENGTH=$2 ; shift 2 ;;
		-tuner) TUNER=$2 ; shift 2;;
		-filename) FILENAME=$2 ; shift 2;;
		-id) ID=$2 ;shift 2;;
		-wbs) WBS=$2 ;shift 2;;
		-usenet) UN=1 ;shift ;;
		-scp) SCP=1 ;shift ;;
		-ftp) FTP=1 ;shift;;
		-nzbmatrix) NZB=1 ;shift;;
		-help) help ; exit ;;
		*) break ;;
	esac
done



function ctrl_c() {
        echo "** Trapped CTRL-C"
	rm /tmp/tuner$TUNER
	echo "See Ya!"
	exit
}

if [ -e "/tmp/tuner${TUNER}" ]; then
	echo "Uh Oh!"
	echo "The show ${FILENAME} failed to record"> /tmp/message
	EMAILMESSAGE="/tmp/message"
	EMAIL="john@sipmeeting.com"
	SUBJECT="${FILENAME} Failed"
	/bin/mail -s "$SUBJECT" "$EMAIL" < $EMAILMESSAGE
	exit
fi


if [ "$FTP" = "1" ]; then
	echo "Will FTP to: $FTPHOST:$FTPDIR"
fi
if [ "$SCP" = "1" ]; then
	echo "Will SCP to: $SCPUSERNAME@$SCPHOST:$SCPBASE"
fi
if [ "$NZB" = "1" ]; then
	echo "Will automate a post to nzb matrix"
fi


touch /tmp/tuner$TUNER


#do some work to support more then 3 tuners (6 max)
#ATUNER (Actual Tuner)
#hdhomerun_ip is now using the device number
if [ $TUNER -gt 2 ]; then
	hdhomerun_ip=$hdhomerun_ip2
	ATUNER=$(expr $TUNER - 3)
else
	hdhomerun_ip=$hdhomerun_ip1
	ATUNER=$TUNER
fi

LENGTH=$(expr $LENGTH \* 60)

if [ $LENGTH -lt 1 ]; then
	echo "You Must record at least 1 minute"
fi
MINUTES=$(expr $LENGTH / 60)
mkdir -p $DIR/$FILENAME
if [ $? != 0 ]; then
	echo "Failed Making Directory\n"
	exit
fi
if [ $WBS -gt 0 ]; then
	echo "Waiting for: $WBS"
	COUNT=0
	while [ $COUNT -le $WBS ]; do
		COUNT=$(( $COUNT + 1 ))
		echo -ne "$COUNT\r"
		sleep 1
	done
	echo "Done Waiting"
fi
echo "Switching: $hdhomerun_config $hdhomerun_ip set /tuner$ATUNER/vchannel $CHANNEL"
$hdhomerun_config $hdhomerun_ip set /tuner$ATUNER/vchannel $CHANNEL
#{ nice -n -10 $hdhomerun_config $hdhomerun_ip save $ATUNER $DIR/$FILENAME/$FILENAME.mpg & } >  $DIR/$FILENAME/hdhomerun.log 2>&1
{ $hdhomerun_config $hdhomerun_ip save $ATUNER - | nice -n -10 cvlc - --sout "#transcode{audio-sync}:std{mux=ts,dst=$DIR/$FILENAME/$FILENAME.mpg,access=file}" & } >  $DIR/$FILENAME/hdhomerun.log 2>&1
PID=$!
echo "Recording: $DIR/$FILENAME/$FILENAME.mpg From Channel: $CHANNEL Using Tuner: $TUNER For $MINUTES Minutes"
COUNT=0
while [ $COUNT -le $LENGTH ]
do
	COUNT=$(( $COUNT + 1 ))
	PER=`echo "scale=3; $COUNT/$LENGTH" | bc`
	PER=`echo "$PER*100" | bc`
	echo -ne "\r"$PER% Complete >> $DIR/$FILENAME/hdhomerun_watcher.log
	sleep 1
	if [ ! -d "/proc/$PID" ]; then
		echo "We stopped running for some reason $PID" >>  $DIR/$FILENAME/hdhomerun.log
if [ "$ID" != "" ]; then
mysql -u ${mysql_username} -p${mysql_password} tv_record<<EOMYSQL
UPDATE torecord set recording="0" where id="$ID";
EOMYSQL
fi
		rm /tmp/tuner$TUNER
		date >> $DIR/$FILENAME/hdhomerun.log
		echo "We died" >> $DIR/$FILENAME/hdhomerun.log
		exit
	fi
done
echo >> $DIR/$FILENAME/hdhomerun.log
echo -n "Completed " >> $DIR/$FILENAME/hdhomerun.log
date >> $DIR/$FILENAME/hdhomerun.log
echo "Stopping Recording"
kill $PID 2>/dev/null
wait $PID 2>/dev/null
echo "Recording Stopped"
date >> $DIR/$FILENAME/timer
rm /tmp/tuner$TUNER

if [ "$ID" != "" ]; then
echo "Mysql" >> $DIR/$FILENAME/hdhomerun.log
mysql -u $mysql_username -p${mysql_password} tv_record<<EOFMYSQL
UPDATE torecord set recording="0" where id="$ID";
EOFMYSQL
echo "Set the Recording to stopped in MySQL"
fi


echo "Running Comskip"
$wine $comskip_dir/comskip.exe -t --ini $comskip_dir/comskip.ini $DIR/$FILENAME/$FILENAME.mpg > $DIR/$FILENAME/comskip.log 2>&1
COM=$?
echo "Comskip Completed with $COM"
if [ $COM -gt 1 ]; then
	echo "Comskip Failed"
	exit
fi
echo "Starting ProjectX"
$java -jar $projectx_dir/ProjectX.jar -out $DIR/$FILENAME -cut $DIR/$FILENAME/$FILENAME.mpg.Xcl $DIR/$FILENAME/$FILENAME.mpg > $DIR/$FILENAME/projectx.log 2>&1
COM=$?
echo "ProjectX Completed with $?"
if [ $COM != 0 ]; then
	echo "ProjectX Failed"
	exit
fi

echo "Testing for bad GOP (ProjectX needs good GOP (Shame on you TLC :))"
SIZE=`du $DIR/$FILENAME/$FILENAME.m2v`
SIZE=`echo $SIZE | cut -d " " -f 1`
if [ $SIZE -le 102400 ] || [ ! -e "$DIR/$FILENAME/$FILENAME.m2v" ]; then
        echo "GOP Failed, or .m2v file didnt show up, (God Damn TLC)"
	$fixgop $DIR/$FILENAME/$FILENAME.mpg
else
        echo "Looks like we had a valid GOP (At least we got something more then 100 megs)"
fi

echo "Starting FFmpeg"
#$ffmpeg -i $DIR/$FILENAME/$FILENAME.ac3 -i $DIR/$FILENAME/$FILENAME.m2v -vcodec libx264 -sameq -acodec copy -f matroska -threads 0 -s hd720 -sws_flags lanczos -y -preset fast $DIR/$FILENAME/$FILENAME.mkv > $DIR/$FILENAME/ffmpeg.log 2>&1
HEIGHT=`$mediainfo --Output=XML $DIR/$FILENAME/$FILENAME.mpg |$xml sel -t -m ".//track[@type='Video']" -v "Height"`
HEIGHT=${HEIGHT/ pixels/}
HEIGHT=${HEIGHT/ /}
OLD_HEIGHT=""
if [ "$HEIGHT" = "480" ]; then
	OLD_HEIGHT="480"
fi
$ffmpeg -i $DIR/$FILENAME/$FILENAME.ac3 -i $DIR/$FILENAME/$FILENAME.m2v -pix_fmt yuv420p -vcodec libx264 -preset fast -vprofile high -trellis 2 -crf 20 -acodec copy -s hd720 -threads 0 -acodec ac3 -f mp4 -y $DIR/$FILENAME/$FILENAME.mp4 > $DIR/$FILENAME/ffmpeg.log 2>&1
COM=$?
echo "ffmpeg Completed with $COM"
if [ $COM != 0 ]; then
	echo "FFmpeg Failed"
	exit
fi
echo "Starting mkvmerge"
$mkvmerge -o $DIR/$FILENAME/$FILENAME.mkv $DIR/$FILENAME/$FILENAME.mp4 > $DIR/$FILENAME/mkvmerge.log 2>&1
COM=$?
echo "mkvmerge Completed with $COM"
if [ $COM != 0 ]; then
	echo "Mkvmerge Failed"
	exit
fi

echo Finished!
date >> $DIR/$FILENAME/timer



if [ "$UN" != "" ]; then
	HEIGHT=`$mediainfo --Output=XML $DIR/$FILENAME/$FILENAME.mkv |$xml sel -t -m ".//track[@type='Video']" -v "Height"`
	HEIGHT=${HEIGHT/ pixels/}
	HEIGHT=${HEIGHT/ /}
	if [ "$OLD_HEIGHT" = "480" ]; then
		echo "This video is not HD so set it to 480"
		HEIGHT="480"
	fi

	mv $DIR/$FILENAME/$FILENAME.mkv $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv
	mkdir -p $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264
	$mediainfo $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv > $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/$FILENAME.${HEIGHT}p.hdtv.x264.nfo

	$rar a $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/$FILENAME.${HEIGHT}p.hdtv.x264.rar -vn -v39936000B -m0 -ep1 $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv > $DIR/$FILENAME/rar.log 2>&1
	$par -s384000 -r10 $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/$FILENAME.${HEIGHT}p.hdtv.x264 $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/*.r* > $DIR/$FILENAME/par2create.log 2>&1
	$mangler -c $mangler_config -f $FILENAME.${HEIGHT}p.hdtv.x264 $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/* > $DIR/$FILENAME/newsmangler.log 2>&1


	mv $NZBDIR/newsmangler_$FILENAME.${HEIGHT}p.hdtv.x264.nzb $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.nzb

	if [ "$NZB" != "" ]; then
		TYPE="41"
		if [ "$HEIGHT" = "480" ]; then
			TYPE="6"
		fi

		$ffmpeg -ss 00:00:10 -t 1 -i $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv -f mjpeg $DIR/$FILENAME/$FILENAME.png > $DIR/$FILENAME/ffmpeg_screenshot.log 2>&1
		link=`$curl -F "image=@$DIR/$FILENAME/$FILENAME.png" -F "key=$imgurapi" http://api.imgur.com/2/upload.xml|$xml sel -t -m //upload/links -v original`
		echo $curl --cookie /tmp/nzbmatrix --cookie-jar /tmp/nzbmatrix --user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.7) Gecko/20100105 Shiretoko/3.5.7" -F "action=doupload" -F "imageurl=$link" -F "nfo=@$DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/$FILENAME.${HEIGHT}p.hdtv.x264.nfo" -F "nzb=@$DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.nzb" -F "lang=1" -F "region=0" -F "type=$TYPE" -F "tag[]=7" -F "readbanned=yes" -F "dupecheck=yes" -F "anonycheck=yes" -L -s http://nzbmatrix.com/nzb-upload.php > $DIR/$FILENAME/nzb_post.log 2>&1
		$curl --cookie /tmp/nzbmatrix --cookie-jar /tmp/nzbmatrix --user-agent "Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.7) Gecko/20100105 Shiretoko/3.5.7" -F "action=doupload" -F "imageurl=$link" -F "nfo=@$DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264/$FILENAME.${HEIGHT}p.hdtv.x264.nfo" -F "nzb=@$DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.nzb" -F "lang=1" -F "region=0" -F "type=$TYPE" -F "tag[]=7" -F "readbanned=yes" -F "dupecheck=yes" -F "anonycheck=yes" -L -s http://nzbmatrix.com/nzb-upload.php >> $DIR/$FILENAME/nzb_post.log 2>&1
	fi
	date >> $DIR/$FILENAME/timer
fi
if [ "$SCP" != "" ]; then
        HEIGHT=`$mediainfo --Output=XML $DIR/$FILENAME/$FILENAME.mkv |$xml sel -t -m ".//track[@type='Video']" -v "Height"`
        HEIGHT=${HEIGHT/ pixels/}
        HEIGHT=${HEIGHT/ /}

        mv $DIR/$FILENAME/$FILENAME.mkv $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv
	$scp $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv $SCPUSERNAME@$SCPHOST:"${SCPBASE}"
fi

if [ "$FTP" != "" ]; then
        HEIGHT=`$mediainfo --Output=XML $DIR/$FILENAME/$FILENAME.mkv |$xml sel -t -m ".//track[@type='Video']" -v "Height"`
        HEIGHT=${HEIGHT/ pixels/}
        HEIGHT=${HEIGHT/ /}

        mv $DIR/$FILENAME/$FILENAME.mkv $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv
	#$scp $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv $SCPUSERNAME@$SCPHOST:"${SCPBASE}"
	$ncftpput -u $FTPUSERNAME -p $FTPPASSWORD $FTPHOST $FTPDIR $DIR/$FILENAME/$FILENAME.${HEIGHT}p.hdtv.x264.mkv
fi
